package db

import (
	"github.com/jinzhu/gorm"
	"sell_data_system/servicer/config"
	"fmt"
	"sell_data_system/servicer/entity"
)

var Connect *gorm.DB //db
// InitDB  连接db
func InitDB(isLog bool) (err error)  {
	fmt.Println("InitDB")
  info := &config.DataBaseInfo{
  	DBName:"sell",
  	Host:"",
  	Port:"",
  	Password:"admin",
  	UserName:"root",

  }
    Connect ,err = config.CreateConnection(info)
    if err !=nil {
		fmt.Printf("初始化数据库，错误：%s \n",err.Error())
	   return err
    }
	Connect = Connect.LogMode(isLog) //是否启用日志
	//连接池设置
	//Connect.DB().SetMaxIdleConns(10)
	//Connect.DB().SetMaxOpenConns(1000)
    perr := Connect.DB().Ping()
    if perr != nil {
    	fmt.Printf("初始化数据库，ping错误：%s \n",perr.Error())
	}
    fmt.Println("ping.........")
	if Connect == nil {
		fmt.Println("tb db nil")
	}
    return perr
}
// InitTb 初始化表
func InitTb() {
	if Connect == nil {
		fmt.Println("tb1 db nil")
	}
	tbHandler(&entity.User{},Connect)
	tbHandler(&entity.Department{},Connect)
	tbHandler(&entity.SellOrder{},Connect)
	tbHandler(&entity.StepCommission{},Connect)

}
//tbHandler 表创建适配器
func tbHandler(table InitTable,db *gorm.DB) {
	table.CreateTb(db)
}
//InitTable 创建表
type InitTable interface {
	CreateTb(db *gorm.DB)
}